<script setup lang="ts">
import { provide, ref } from 'vue'
import { onLaunch } from '@dcloudio/uni-app'
import { debugWarn } from '@tuniao/tnui-vue3-uniapp/utils'
import { getGradesApi, getAllGrades } from '@/services/api'
import storageApi from '@/utils/storage'
import { useUserStore } from '@/stores'
const userStore = useUserStore()

const code = ref('')
const globalData = {
  privacyContractName: '', //隐私协议的名字
  showPrivacy: false, //控制隐私弹窗显隐
}
provide('globalData', globalData)

onLaunch(async () => {
  // 如果没有选择年级，默认给接口第一条数据的年级
  if (!storageApi.get('gradeData')) {
    getDefaultGrade()
  }

  // 加载字体
  uni.loadFontFace({
    family: 'tuniao-xiaowei',
    source:
      'url("https://resource.tuniaokj.com/images/vue3-template/template2-website/font/tuniao-xiaowei.ttf")',
    fail: (err) => {
      debugWarn('load-font', `加载字体失败: ${err}`)
      console.error(err)
    },
  })

  //登录
  await handleLogin()
  //检测设备连接状态


  //隐私授权
  getPrivacy()
})

//老版本-个人中心入口，年级
// const getDefaultGrade = () => {
//   getGradesApi(0).then((res) => {
//     const { code, data } = res
//     if (code === 0) {
//       storageApi.set('gradeData', data[0])
//       storageApi.set('currentListItemIndex', 0)
//       storageApi.set('currentTabIndex', 0)
//     }
//   })
// }

//新版本-年级
const getDefaultGrade = () => {
  getAllGrades().then((res) => {
    const { code, data } = res
    if (code === 0) {
      storageApi.set('gradeData', data.grade_objects[0].grade_list[0])
      storageApi.set('currentListItemIndex', 1)
    }
  })
}

const handleLogin = async () => {
  await wrapWxLoginAsPromise()
  await getAccessToken()

}

const getAccessToken = () => {
  let params = {
    tag: 'wechat_miniprogram',
    client_id: '74afa8533379ccde1bc8',
    code: code.value,
  }
  uni.request({
    url: 'https://auth.xming-ai.com/api/login/oauth/access_token',
    method: 'POST',
    data: params,
    header: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    success: (res) => {
      const { access_token, token_type } = res.data
      storageApi.set('token', `${token_type} ${access_token}`)
	  // 获取是否绑定设备
	  userStore.checkUserSn()
    userStore.getUserInfo()
    },
  })
}

const wrapWxLoginAsPromise = () => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: (res) => {
        code.value = res.code
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}
//隐私授权
const getPrivacy = () => {
  return new Promise((resolve, reject) => {
    wx.getPrivacySetting({
      success(res) {
        console.log(
          '是否需要授权：',
          res.needAuthorization,
          '隐私协议的名称为：',
          res.privacyContractName
        )
        if (res.needAuthorization) {
          globalData.privacyContractName = res.privacyContractName
          globalData.showPrivacy = true
        } else {
          globalData.showPrivacy = false
        }
      },
    })
  })
}
</script>
<style lang="scss">
@import '@tuniao/tn-style/dist/uniapp/index.css';
@import '@/static/css/custom.scss';
page {
  background-color: #f1f5fb;
  // padding-bottom: 20rpx;
}
</style>
